package util;

import java.util.ArrayList;
import java.util.Iterator;

public class StrikeCount {
    private static int STRIKE_COUNT = 4;
    
    public static void main(String[] args) {
        ArrayList<byte[]> list = new ArrayList<byte[]>();

        for (int i = 0; i < Math.pow(3, STRIKE_COUNT); i++) {

            byte[] number = new byte[STRIKE_COUNT];
            int a = i;

            for (int j = 0; j < STRIKE_COUNT; j++) {
                number[j] = (byte) (a % 3);
                a = a / 3;
            }
            list.add(number);
        }

        ArrayList<byte[]> sortedList = new ArrayList<byte[]>();
        sortedList.add(list.get(0));
        list.remove(0);

        while (list.size() > 0) {
            int index = findNext(sortedList.get(sortedList.size() - 1), list);
            if (index >= 0) {
                sortedList.add(list.get(index));
                list.remove(index);
            } else {
                sortedList.add(list.get(0));
                list.remove(0);
            }
        }

        for (int i = 0; i < sortedList.size(); i++) {
            String str = "";
            byte[] number = sortedList.get(i);
            if (i > 0 && isNext(sortedList.get(i - 1), number)) {
                str = Byte.toString(number[STRIKE_COUNT - 1]);
                System.out.print(str);
            } else {
                System.out.println();
                for (int j = 0; j < STRIKE_COUNT; j++) {
                    str += Byte.toString(sortedList.get(i)[j]);
                }
                System.out.print(str);
            }
        }

        System.out.println();
        System.out.flush();
        return;
    }

    private static int findNext(byte[] number, ArrayList<byte[]> list) {
        for (int i = 0; i < list.size(); i++) {
            byte[] item = list.get(i);
            if (isNext(number, item))
                return i;
        }
        return -1;
    }

    private static boolean isNext(byte[] number, byte[] next) {
        boolean f = true;
        for (int j = 0; j < STRIKE_COUNT - 1; j++) {
            f = f && number[j + 1] == next[j];
        }
        return f;
    }
}
